﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxCallback;
using TireService.Data;
using System.Configuration;
using System.Web.Security;

namespace TireService.Website.Webshop
{
    public partial class Kurv : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BindShoppingCart();
        }

        private void BindShoppingCart() 
        {
            ShoppingCartActions cartActions = new ShoppingCartActions();

            gvShoppingCart.DataSource = cartActions.GetCartItems();
            gvShoppingCart.DataBind();
        }

        /// <summary>
        /// Callback function that add subscription to shopping cart
        /// </summary>
        protected void callBackAddSubscription_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get subscription
                int SubcriptionId = Convert.ToInt32(e.Parameter);

                ShoppingCartActions cartActions = new ShoppingCartActions();

                // Function - remove if product id 1-7 exists in shoppingcart
                for (int i = 1; i < 8; i++)
                {
                    cartActions.RemoveFromCart(i);
                }

                // Add subscription
                cartActions.AddToCart(SubcriptionId, 1);

                // Function - remove if product id 0 or -1 exists in shoppingcart
                cartActions.RemoveFromCart(0);
                cartActions.RemoveFromCart(-1);
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        /// <summary>
        /// Callback function that add shippingdelivery to shopping cart
        /// </summary>
        protected void callBackAddDelivery_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                ShoppingCartActions cartActions = new ShoppingCartActions();

                // Function - remove if product id 0 or -1 exists in shoppingcart
                cartActions.RemoveFromCart(0);
                cartActions.RemoveFromCart(-1);

                // Add shipping
                cartActions.AddToCart(Convert.ToInt32(e.Parameter), 1);

                // Function - remove if product id 1-7 exists in shoppingcart
                for (int i = 1; i < 8; i++)
                {
                    cartActions.RemoveFromCart(i);
                }
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        /// <summary>
        /// Callback function that creates order
        /// </summary>
        protected void callBackCreateOrder_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                // 0: Deliveryoptions (0: Mobile, 1: Shipping)
                // 1: Subscription (1-6: SubscriptionId)
                // 2: Delivery (0: Private, -1: Business)
                // 3: Name
                // 4: Address
                // 5: ZipCode
                // 6: City
                // 7: Phone
                // 8: Email
                // 9: Change delivery address (true/false)
                // 10: Delivery Name
                // 11: Delivery Address
                // 12: Delivery ZipCode
                // 13: Delivery City
                // 14: Shipment delivery options (0-5: Carport, ect.)
                // 15: Delivery note
                string[] param = e.Parameter.Split('|');

                // Define system userid (Used for logging)
                Guid SystemUserId = new Guid(ConfigurationManager.AppSettings["SystemUserId"].ToString()); // System ID - Jannik79

                TireServiceDB db = new TireServiceDB();

                // Create customer
                Customer customer = new Customer();

                // Declare values
                int DeliveryOption = Convert.ToInt32(param[0]);
                int customerid = 0;
                bool parentcompany = false;
                int? parentcustomerid = null;
                bool parentpayinvoice = false;
                string companyname = null;
                string companynumber = null;
                string name = param[3];
                string address = param[4];
                string zipcode = param[5];
                string city = param[6];
                int countryid = Convert.ToInt32(0); // HACK: Denmark
                bool onprimaryaddress = true;
                string secondaryaddress = param[4];
                string secondaryzipcode = param[5];
                string secondarycity = param[6];
                string phone1 = param[7];
                int phone1type = Convert.ToInt32(0); // HACK: do not know if it is a mobile of fixed line
                int? phone2type = null;
                string phone2 = string.Empty;
                string email = param[8];

                string deliverydetails = address + ", " + zipcode + " " + city;

                CustomerBLL customerBLL = new CustomerBLL();
                customerBLL.UpdateCustomer(
                                            db,
                                            customer,
                                            customerid,
                                            parentcompany,
                                            parentcustomerid,
                                            parentpayinvoice,
                                            false,
                                            companyname,
                                            companynumber,
                                            name,
                                            address,
                                            zipcode,
                                            city,
                                            countryid,
                                            secondaryaddress,
                                            secondaryzipcode,
                                            secondarycity,
                                            phone1,
                                            phone1type,
                                            phone2,
                                            phone2type,
                                            email,
                                            onprimaryaddress,
                                            true,
                                            false,
                                            false,
                                            true
                                        );

                // Initiate customer subscription business logic
                CustomerSubscriptionBLL customersubscriptionBLL = new CustomerSubscriptionBLL();

                // Initiate E-conomic interface
                EconomicInterface ecoInterface = new EconomicInterface();

                // Initiate shopping cart actions
                ShoppingCartActions cartActions = new ShoppingCartActions();

                // Prepare customersubscription
                CustomerSubscription customersubscription = new CustomerSubscription();

                // Create orderline for invoicing
                List<EconomicInterface.EcoOrderLine> orderlines = new List<EconomicInterface.EcoOrderLine>();

                if (DeliveryOption == 0)
                {
                    // Mobile solution

                    CartItem cartItem = cartActions.GetCartItems().Where(p => p.ProductId > 0 & p.ProductId < 8).Single();

                    int SubscriptionId = cartItem.ProductId;

                    // Create subscription
                    // Get subscription 
                    Subscription subscription = db.GetSubscription(SubscriptionId);

                    // Calculate subscription renew date
                    // Renewal dates: 01/03 and 01/09
                    //DateTime LastRenewalDate = Convert.ToDateTime(DateTime.Now);
                    DateTime LastRenewalDate = customersubscriptionBLL.CalculateLastRenewalDate(Convert.ToDateTime(DateTime.Now));
                    DateTime NextRenewalDate = customersubscriptionBLL.CalculateNextRenewalDate(LastRenewalDate, subscription);
                    decimal Price = cartItem.UnitPrice;
                    bool BalancingIncluded = subscription.BalancingIncluded;

                    // Create customersubscription
                    customersubscriptionBLL.UpdateCustomerSubscription(db, customersubscription, customer, 0, subscription.SubscriptionId, LastRenewalDate, NextRenewalDate, false, BalancingIncluded, Price, SystemUserId, true, "Bestilling af abonnement og bil");
                }
                else
                {
                    // Shipping solution

                    // 9: Change delivery address (true/false)
                    // 10: Delivery Name
                    // 11: Delivery Address
                    // 12: Delivery ZipCode
                    // 13: Delivery City
                    // 14: Shipment delivery options (0-5: Carport, ect.)
                    // 15: Delivery note
                    bool ChangeDeliveryAddress = Convert.ToBoolean(param[9]);

                    if (ChangeDeliveryAddress)
                    {
                        // Change delivery address
                        
                        deliverydetails = param[10] + ", " + param[11] + ", " + param[12] + " " + param[13];
                    }

                    deliverydetails += "<br>Leverings muligheder: " + param[14] + " " + param[15];
                    
                }

                // Commit changes to database
                db.SubmitChanges();

                // Create debtor in E-conomic
                ecoInterface.CreateDebtor(customer, db);

                // Create orderlines for tire products
                foreach (CartItem cartItem in cartActions.GetCartItems().Where(p => p.ProductId > 1000))
                {
                    // Invoicing for tirepick up
                    EconomicInterface.EcoOrderLine orderline_otherproduct = new EconomicInterface.EcoOrderLine();
                    orderline_otherproduct.ProductNumber = 200; // HACK: hardcoded
                    orderline_otherproduct.Description = cartItem.Description;
                    orderline_otherproduct.Quantity = cartItem.Quantity;
                    orderline_otherproduct.UnitPrice = (cartItem.UnitPrice * Convert.ToDecimal(0.8)); // TODO: Check if VAT if working correctly

                    orderlines.Add(orderline_otherproduct);
                }

                // Create invoice lines for subscriptions
                foreach (CartItem cartItem in cartActions.GetCartItems().Where(p => p.ProductId > 0 & p.ProductId < 8))
                {
                    // For Subscription
                    EconomicInterface.EcoOrderLine orderline = new EconomicInterface.EcoOrderLine();
                    orderline.ProductNumber = cartItem.ProductId; 
                    orderline.Description = cartItem.Description;
                    orderline.Quantity = cartItem.Quantity;
                    orderline.UnitPrice = (cartItem.UnitPrice * Convert.ToDecimal(0.8));

                    orderlines.Add(orderline);                    
                }

                // Create invoice lines for shipping
                foreach (CartItem cartItem in cartActions.GetCartItems().Where(p => p.ProductId == 0 | p.ProductId == -1))
                {
                    // HACK: NOT A GOOD SOLUTION
                    int productnumber = 13; // Private delivery
                    string description = "Levering privat";
                    decimal price = (199 * Convert.ToDecimal(0.8)); // Exclude VAT
                    if (cartItem.ProductId == 0)
                    {
                        productnumber = 13; // Private delivery
                        description = "Levering privat";
                        price = (199 * Convert.ToDecimal(0.8)); // Exclude VAT
                    }
                    if (cartItem.ProductId == -1)
                    {
                        productnumber = 14; // Business delivery
                        description = "Levering erhverv";
                        price = (99 * Convert.ToDecimal(0.8)); // Exclude VAT
                    }

                    // For Subscription
                    EconomicInterface.EcoOrderLine orderline = new EconomicInterface.EcoOrderLine();
                    orderline.ProductNumber = productnumber;
                    orderline.Description = description;
                    orderline.Quantity = 1; 
                    orderline.UnitPrice = price; 

                    orderlines.Add(orderline);
                }

                // Create invoice in e-conomic
                string invoiceid = ecoInterface.CreateInvoice(db, customer.CustomerId, orderlines, true);

                // Prepare email
                EmailNotificationServices emailService = new EmailNotificationServices();

                //try
                //{
                //    // Create user
                //    MembershipUser user = Membership.CreateUser(customer.Email, customer.Phone1.ToString(), customer.Email);

                //    // Add user to customer role
                //    Roles.AddUserToRole(user.UserName, "Kunde");

                //    customer.UserId = new Guid(user.ProviderUserKey.ToString());

                //    db.SubmitChanges();

                //    // Send email to user with user information
                //    emailService.Customer_UserInformation_SendCustomerEmail(customer.Email, customer.Name, user.UserName, customer.Phone1.ToString(), customer.CustomerId);
                //}
                //catch (Exception ex)
                //{
                //    // Nothing, but error does not stop signup process for customer

                //    // Send email to mobil hjulskift with error
                //    string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                //    string message = String.Format("Systemet fejlede ved forsøg på at oprette kunde login<br><br>Email: {0}<br><br>Fejl: {1}", customer.Email, ex.Message);


                //    Shared emailBLL = new Shared();
                //    emailBLL.SendEmail(emailaddress, emailaddress, message, "Fejl ved oprettelse af brugerlogin", true, test, null, null, null);
                //}

                //// Send email with order confirmation to customer
                //string BookingLink = Convert.ToString(ConfigurationManager.AppSettings["BookingURL"]) + "?uid=" + customer.UserId.ToString();
                //emailService.Customer_OrderConfirmationAndInvoice_SendCustomerEmail(customer.CustomerId, customer.Email, customer.Name, invoiceid, ecoInterface.GetInvoice(Convert.ToInt32(invoiceid)), "Faktura" + invoiceid + ".pdf", Convert.ToString((int)Shared.PaymentGateWayActions.InitiatePayment), Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]), BookingLink);

                // Return log on task creation to finance email
                string logHTML = "<b>Kundenr: " + customer.CustomerId.ToString() + "<br><b>Navn: " + customer.Name + "<br><br>";
                if (DeliveryOption == 1)
                {
                    // Add delivery details
                    logHTML += deliverydetails;
                }
                logHTML += "Webshop ordre</b><br><table><tr><td>ItemId</td><td>CartId</td><td>Description</td><td>UnitPrice</td><td>Quantity</td><td>TotalPrice</td><td>ProductId</td></tr>";
                foreach (CartItem cartItem in cartActions.GetCartItems())
                {
                    logHTML += "<tr><td>" + cartItem.ItemId + "</td><td>" + cartItem.CartId + "</td><td>" + cartItem.Description + "</td><td>" + cartItem.UnitPrice.ToString() + "</td><td>" + cartItem.Quantity.ToString() + "</td><td>" + cartItem.TotalPrice.ToString() + "</td><td>" + cartItem.ProductId.ToString() + "</td></tr>";
                }
                logHTML += "</table>";

                string Subject = "Webshop ordre - Kundenr: " + customer.CustomerId.ToString();
                emailService.SendSalesInternalEmailNotification(Subject, logHTML);

                db.Dispose();

                // Return payment link
                e.Result = string.Format("{0}?cid={1}&iid={2}&action={3}", Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]), customer.CustomerId, invoiceid, Convert.ToString((int)Shared.PaymentGateWayActions.InitiatePayment));
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        protected void gvShoppingCart_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            BindShoppingCart();
        }


        private void Test() 
        {
            decimal FreightCost = 100;

            // Calculate total order price
            decimal TotalOrderPrice = FreightCost + Convert.ToDecimal(gvShoppingCart.GetTotalSummaryValue(gvShoppingCart.TotalSummary["TotalPrice"]));
        }
    }
}